package com.myblog.controller.admin;

import com.myblog.service.LabelService;
import com.myblog.enums.SysEnum;
import com.myblog.execption.SystemErrorException;
import com.myblog.entity.Label;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin")
@ApiModel("标签控制层")
public class LabelController {

    private final static String ADMIN_LABEL = "admin/label";
    private final static String REDIRECT_LIST = "redirect:/" + ADMIN_LABEL;

    @Autowired
    private LabelService labelService;

    @ApiOperation("查询标签列表")
    @GetMapping("/label")
    public String list(Model model) {
        model.addAttribute("labelList", labelService.list());
        return ADMIN_LABEL;
    }

    @ApiOperation("保存标签")
    @PostMapping("/label")
    public String save0update(@Validated Label label, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new SystemErrorException(SysEnum.ILLEGAL_ERROR);
        }
        labelService.save(label);
        return REDIRECT_LIST;
    }

    @ApiOperation("标签数据回显")
    @PutMapping("/label")
    @ResponseBody
    public Object listById(@RequestParam(value = "id", required = true) Integer id) {
        Label label = labelService.listById(id);
        if (label == null) {
            throw new SystemErrorException(SysEnum.ILLEGAL_LABEL);
        }
        return label;
    }

    @ApiOperation("删除标签")
    @DeleteMapping("/label")
    public String del(@RequestParam(value = "id", required = true) Integer lid) {
        labelService.del(lid);
        return REDIRECT_LIST;
    }
}
